﻿Imports System
Imports System.CodeDom
Imports System.Globalization
Imports System.Runtime.CompilerServices
Imports System.Text

Namespace System.Workflow.Activities.Rules
    Friend Class CodeDomStatementWalker
        ' Methods
        Friend Shared Sub AnalyzeUsage(ByVal analysis As RuleAnalysis, ByVal statement As CodeStatement)
            CodeDomStatementWalker.GetStatement(statement).AnalyzeUsage(analysis)
        End Sub

        Friend Shared Function Clone(ByVal statement As CodeStatement) As CodeStatement
            If (statement Is Nothing) Then
                Return Nothing
            End If
            Return CodeDomStatementWalker.GetStatement(statement).Clone
        End Function

        Friend Shared Sub Decompile(ByVal stringBuilder As StringBuilder, ByVal statement As CodeStatement)
            CodeDomStatementWalker.GetStatement(statement).Decompile(stringBuilder)
        End Sub

        Friend Shared Sub Execute(ByVal execution As RuleExecution, ByVal statement As CodeStatement)
            CodeDomStatementWalker.GetStatement(statement).Execute(execution)
        End Sub

        Private Shared Function GetStatement(ByVal statement As CodeStatement) As RuleCodeDomStatement
            Dim type As Type = statement.GetType
            If (type Is GetType(CodeExpressionStatement)) Then
                Return ExpressionStatement.Create(statement)
            End If
            If (type Is GetType(CodeAssignStatement)) Then
                Return AssignmentStatement.Create(statement)
            End If
            Dim exception As New NotSupportedException(String.Format(CultureInfo.CurrentCulture, Messages.CodeStatementNotHandled, New Object() { statement.GetType.FullName }))
            exception.Data.Item("ErrorObject") = statement
            Throw exception
        End Function

        Friend Shared Function Match(ByVal firstStatement As CodeStatement, ByVal secondStatement As CodeStatement) As Boolean
            If ((firstStatement Is Nothing) AndAlso (secondStatement Is Nothing)) Then
                Return True
            End If
            If ((firstStatement Is Nothing) OrElse (secondStatement Is Nothing)) Then
                Return False
            End If
            If (Not firstStatement.GetType Is secondStatement.GetType) Then
                Return False
            End If
            Return CodeDomStatementWalker.GetStatement(firstStatement).Match(secondStatement)
        End Function

        Friend Shared Function Validate(ByVal validation As RuleValidation, ByVal statement As CodeStatement) As Boolean
            Return CodeDomStatementWalker.GetStatement(statement).Validate(validation)
        End Function


        ' Nested Types
        Private Delegate Function WrapperCreator(ByVal statement As CodeStatement) As RuleCodeDomStatement
    End Class
End Namespace

